<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\EloquentSortable\Sortable;

class DepartmentCategory extends Model implements Sortable
{
    use ModelTree, HasDateTimeFormatter;
    use HasFactory;

    // 设置排序字段，默认order
    protected $orderColumn = 'order';

    protected $fillable = [
        'id',
        'title',
        'depth',
        'parent_id',
        'is_show',
        'order',
    ];

    public function childrenRelation(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
    public function projects(){
        return $this->hasMany(Project::class , 'department_id' ,'id');
    }

    /**
     * Get options for Select field in form.
     *
     * @param \Closure|null $closure
     * @param null $rootText
     * @param boolean $showRoot
     * @return array
     */
    public static function selectOptions(\Closure $closure = null, $rootText = null, bool $showRoot = true)
    {
        $rootText = $rootText ?: admin_trans_label('root');

        $options = (new static())->withQuery($closure)->buildSelectOptions();
        $options = collect($options);
        if ($showRoot)
            $options = $options->prepend($rootText, 0);
        return $options->all();
    }

    public static function oneLevelOptions($rootText = null, bool $showRoot = true)
    {
        $c = self::query()
            ->where('depth', '=', 1)
            ->get();
        $rootText = $rootText ?: admin_trans_label('root');

        $options = (new static())->buildSelectOptions($c->toArray());
        $options = collect($options);
        if ($showRoot)
            $options = $options->prepend($rootText, 0);
        return $options->all();
    }
    public static function twoLevelOptions($rootText = null, bool $showRoot = true)
    {
        $c = self::query()
            ->where('depth', 2)
            ->get()
        ->pluck("title","id");
        return $c;
        $rootText = $rootText ?: admin_trans_label('root');

        $options = (new static())->buildSelectOptions($c->toArray());
        $options = collect($options);
        if ($showRoot)
            $options = $options->prepend($rootText, 0);
        return $options->all();
    }
}
